package com.kaishun.study.mybatis;

import org.apache.ibatis.builder.IncompleteElementException;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.builder.xml.XMLStatementBuilder;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.parsing.XPathParser;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;

/**
 * @Package: com.kaishun.study.mybatis
 * @ClassName: MyBatisTest
 * @Author: zhoukaishun
 * @CreateTime: 2022/5/30 15:32
 * @Description:
 */
public class MyBatisTest {

    /**
     *
     * @param sqlSessionFactory sqlSessionFactory
     * @param executeClass 执行动态 mapper 的代理接口类
     * @param xml mapper 标签，比如：<select id="dynamicQuery">select * from table</select>
     * @param nodeType mapper 节点类型，比如：/select
     */
    public void dynamicParse(SqlSessionFactory sqlSessionFactory, Class<?> executeClass, String xml, String nodeType) {
        Configuration configuration = sqlSessionFactory.getConfiguration();
        MapperBuilderAssistant mapperBuilderAssistant = new MapperBuilderAssistant(configuration, xml);
        mapperBuilderAssistant.setCurrentNamespace(executeClass.getName());
        XNode xNode = new XPathParser(xml).evalNode(nodeType);
        XMLStatementBuilder xmlStatementBuilder = new XMLStatementBuilder(configuration, mapperBuilderAssistant, xNode, configuration.getDatabaseId());
        try {
            xmlStatementBuilder.parseStatementNode();
        } catch (IncompleteElementException e) {
            /**
             * 这里值得注意，此异常是元素不完整异常，应该是 mapper 中存在元素依赖导致的
             * 官方是先保存起来，后面再解析一次，保存代码如下所示:
             * this.configuration.addIncompleteStatement(xmlStatementBuilder);
             *
             * 再次解析的方法是：
             * parsePendingStatements();
             *
             * 这里就直接抛异常了
             */
            throw new RuntimeException();
        }
    }


}

